package com.lbh.scheduler;

import java.util.HashMap;
import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.lbh.job.TwoJob;

/**
 * 运用cron的调度器
 * @author leimo
 *
 */
public class TwoScheduler {
	public static TwoScheduler two = new TwoScheduler();

	public static void main(String[] args) {
		Map<Object, Object> map = two.getScheduler("job2", "group2", "trigger2", TwoJob.class, "0/5 * * * * ? ");
		JobDetail job = (JobDetail) map.get("job");
		CronTrigger trigger = (CronTrigger) map.get("trigger");
		Scheduler scheduler = (Scheduler) map.get("scheduler");

		two.schedulerStart(scheduler, trigger, job);
		try {
			Thread.sleep(60000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		two.schedulerEnd(scheduler);
	}

	/**
	 * 创建
	 * 
	 * @param jobName
	 * @param groupName
	 * @param triggerName
	 * @param cla
	 * @param cron
	 * @return
	 */
	public Map<Object, Object> getScheduler(String jobName, String groupName, String triggerName, Class cla,
			String cron) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		Scheduler scheduler = null;
		try {
			scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.start();
			JobDetail job = JobBuilder.newJob(cla).withIdentity(jobName, groupName).build();
			CronTrigger trigger = TriggerBuilder.//
					newTrigger().//
					withIdentity(triggerName, groupName).//
					startNow().//
					withSchedule(//
							CronScheduleBuilder.//
									cronSchedule(cron))//
					.build();
			map.put("job", job);
			map.put("trigger", trigger);
			map.put("scheduler", scheduler);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 开启
	 * 
	 * @param scheduler
	 * @param trigger
	 * @param job
	 */
	public void schedulerStart(Scheduler scheduler, CronTrigger trigger, JobDetail job) {
		try {
			scheduler.scheduleJob(job, trigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭
	 * 
	 * @param scheduler
	 */
	public void schedulerEnd(Scheduler scheduler) {
		try {
			scheduler.shutdown();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
}
